-- Blacksmith
-- Created by chengb Feb/3/2016
-- 工坊格子

require "game/ui/form/blacksmith/UIDungeonBlacksmith"

-- 初始化
function initBlacksmith(self)
    if self.gridData.blacksmith_type == "special" then
        -- 初始化特殊工坊
        initSpecialBlacksmith(self);
        return;
    end

    self.item:removeAllChildren();

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 获取格子位置
            local pos = self.gridData:getPos();

            -- 音效
            AudioM.playFx("workshop_open_ui");

            -- 打开工坊界面
            if UIMgr.getCurrentScene():isOpen("UIDungeonBlacksmith2") then
                UIMgr.getCurrentScene():removeFormByName("UIDungeonBlacksmith2");
            end
            local uiDungeonBlacksmith2 = UIDungeonBlacksmith2.create(pos);
            UIMgr.getCurrentScene():addForm(uiDungeonBlacksmith2);
        end
    end

    -- 工坊图标
    local icon = self.gridData.icon or "blacksmith";
    icon = getLevelItemIconPath(icon);

    self.icon = ccui.ImageView:create(icon);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
end

-- 初始化特殊工坊
function initSpecialBlacksmith(self)
    self.item:removeAllChildren();

    local function viewFunc()
        local pos = self.gridData:getPos();

        -- 打开工坊界面
        UIMgr.getCurrentScene():removeFormByName("UIDungeonBlacksmith2");
        local uiDungeonBlacksmith2 = UIDungeonBlacksmith2.create(pos);
        UIMgr.getCurrentScene():addForm(uiDungeonBlacksmith2);
    end

    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 音效
            AudioM.playFx("ui_open1");

            if DungeonInstanceM.isInInstance() and
                not DungeonM.isAllMonsterDead() then
                -- 如果在副本中，需要击杀所有怪物方可拾取
                self:openBuildingView(nil, -20, buildingInfo["dialog2"], getLocStr("btn_text_leave"));
                return;
            end

            -- 显示建筑查看界面
            self:openBuildingView(viewFunc);
        end
    end

    -- 工坊图标
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;
end
